package com.xx.douyi.controller;

import cn.hutool.core.codec.Base64;
import com.xx.douyi.service.DouYinService;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.websocket.server.PathParam;
import java.net.HttpCookie;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/dy")
public class DouYinController {
    @Autowired
    private DouYinService douYinService;
    @GetMapping("/getLive")
    public Map getLive(HttpServletRequest request){
        Map live = douYinService.getLive(request);
        return live;
    }
    @SneakyThrows
    @GetMapping(value ="/getQrCode",produces = MediaType.IMAGE_JPEG_VALUE)
    public byte[] getQrCode(){
        Map qrCode = douYinService.getQrCode();
        Map data = (Map) qrCode.get("data");
        System.out.printf((String) data.get("token"));
        return Base64.decode(String.valueOf(data.get("qrcode")));
    }

    public Map getCode(){
        Map qrCode = douYinService.getQrCode();
        Map data = (Map) qrCode.get("data");
        return data;
    }
    @GetMapping("/checkQrConnect/{token}")
    public Map checkQrConnect(@PathVariable String token){
        return douYinService.checkQrConnect(token);
    }
    @PostMapping("/getStream")
    public Map getStream(@RequestParam Map<String,String> map){
        return douYinService.getStream(map.get("cookie"),map.get("deviceId"));
    }
    @GetMapping("/getUsers")
    public Map getUser(HttpServletRequest request){
        Map users = douYinService.getUsers(request);
        return users;
    }
    @GetMapping("/cookie")
    public void createCookie(HttpServletResponse response, HttpServletRequest request){
        List<HttpCookie> httpCookies = douYinService.GoDy();
        Cookie[] cookies = request.getCookies();
        if (cookies != null){
            for (Cookie cookie : cookies) {
                if(cookie.getName().equals(httpCookies.get(0).getName())){
                    return;
                }
            }
        }
        for (HttpCookie cookie : httpCookies) {
            Cookie c = new Cookie(cookie.getName(), cookie.getValue());
            c.setMaxAge((int) cookie.getMaxAge());
            response.addCookie(c);
        }
    }
    @GetMapping("/userAllVideo")
    public Map getUserAllVideo(String url,@RequestParam(value = "max_cursor",defaultValue = "0",required = false) String maxCursor){
        Map list = douYinService.getUserAllVideo(url,maxCursor);
        return list;
    }
}
